package com.jrx.anytxn.accounting.job.mergeFile.step;

import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import com.jrx.anytxn.common.uitl.StringUtils;
import org.springframework.batch.item.ItemWriter;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

public class MergeFileWriter implements ItemWriter<GaVoucherInfo> {
    private Map<String, GaVoucherInfo> mergeMap;

    public MergeFileWriter(Map<String, GaVoucherInfo> mergeMap) {
        this.mergeMap = mergeMap;
    }

    private static ReentrantLock lock = new ReentrantLock();


    @Override
    public void write(List items) {
        Map<String, List<GaVoucherInfo>> gaVoucherInfoMap = ((List<GaVoucherInfo>) items).stream().collect(Collectors.groupingBy(MergeFileWriter::fetchGroupKey));
        gaVoucherInfoMap.forEach(this::putMergeFile);
    }

    /**
     * 获取，修改缓存map加锁
     * @param key
     * @param list
     */
    private void putMergeFile(String key, List<GaVoucherInfo> list) {
        BigDecimal amt = list.stream().map(GaVoucherInfo::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal salesAmt = list.stream().map(GaVoucherInfo::getSalesAmt).reduce(BigDecimal.ZERO,BigDecimal::add);

        lock.lock();
        try {
            if (null == mergeMap.get(key)) {
                GaVoucherInfo gaVoucherInfo = new GaVoucherInfo();
                gaVoucherInfo.setTenantId(list.get(0).getTenantId());
                gaVoucherInfo.setOrganizationId(list.get(0).getOrganizationId());
                gaVoucherInfo.setBusinessDate(list.get(0).getBusinessDate());
                gaVoucherInfo.setSubjectId(list.get(0).getSubjectId());
                gaVoucherInfo.setSign(list.get(0).getSign());
                String priceCode = list.get(0).getPriceTxaCode();
                priceCode = StringUtils.isNotBlank(priceCode) ? priceCode : "";
                gaVoucherInfo.setPriceTxaCode(priceCode);
                gaVoucherInfo.setAmount(amt);
                gaVoucherInfo.setSalesAmt(salesAmt);
                mergeMap.put(key, gaVoucherInfo);
            } else {
                GaVoucherInfo gaVoucherInfo =  mergeMap.get(key);
                gaVoucherInfo.setAmount(gaVoucherInfo.getAmount().add(amt));
                gaVoucherInfo.setSalesAmt(gaVoucherInfo.getSalesAmt().add(salesAmt));

            }
        } finally {
            lock.unlock();
        }

    }

    private static String fetchGroupKey(GaVoucherInfo voucherInfo){
        String priceCode = voucherInfo.getPriceTxaCode();
        priceCode = StringUtils.isNotBlank(priceCode) ? priceCode : "";
        return voucherInfo.getSubjectId() +"#"+ voucherInfo.getSign()+"#"+voucherInfo.getPriceTxaCode();
    }
}
